﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;

namespace com.igetui.api.openservice.utils
{
	// Token: 0x02000036 RID: 54
	internal class ApiUrlRespectUtil
	{
		// Token: 0x060004CD RID: 1229 RVA: 0x0000B63C File Offset: 0x0000983C
		public static string getFastest(string appKey, List<string> hosts)
		{
			ApiUrlRespectUtil.flag = false;
			ApiUrlRespectUtil.url = "";
			int num = hosts.Count<string>();
			if (num == 0)
			{
				throw new Exception("can't get fastest host from empty list");
			}
			if (num == 1)
			{
				return hosts[0];
			}
			if (!ApiUrlRespectUtil.appFastUrlDict.ContainsKey(appKey))
			{
				object obj = ApiUrlRespectUtil.thisLock;
				lock (obj)
				{
					if (!ApiUrlRespectUtil.appFastUrlDict.ContainsKey(appKey))
					{
						//new Thread[num];
						for (int i = 0; i < num; i++)
						{
							new Thread(new ParameterizedThreadStart(ThreadMethod))
							{
								IsBackground = true
							}.Start(hosts[i]);
						}
						while (!ApiUrlRespectUtil.flag)
						{
							Thread.Sleep(1);
						}
						ApiUrlRespectUtil.appFastUrlDict[appKey] = ApiUrlRespectUtil.url;
					}
				}
			}
			return ApiUrlRespectUtil.appFastUrlDict[appKey];
		}

		// Token: 0x060004CE RID: 1230 RVA: 0x0000B734 File Offset: 0x00009934
		public static void setProxy(HttpProxy p)
		{
			ApiUrlRespectUtil.proxy = p;
		}

		// Token: 0x060004CF RID: 1231 RVA: 0x0000B73C File Offset: 0x0000993C
		private static void ThreadMethod(object ob)
		{
			string requestUriString = (string)ob;
			HttpWebRequest httpWebRequest = null;
			HttpWebResponse httpWebResponse = null;
			try
			{
				httpWebRequest = (WebRequest.Create(requestUriString) as HttpWebRequest);
				WebProxy webProxy = ApiUrlRespectUtil.proxy.getWebProxy();
				if (webProxy != null)
				{
					httpWebRequest.Proxy = webProxy;
				}
				httpWebRequest.Timeout = 30000;
				httpWebRequest.Method = "HEAD";
				httpWebRequest.ProtocolVersion = new Version(1, 1);
				httpWebResponse = (httpWebRequest.GetResponse() as HttpWebResponse);
				if (httpWebResponse.StatusCode == HttpStatusCode.OK && !ApiUrlRespectUtil.flag)
				{
					ApiUrlRespectUtil.flag = true;
					ApiUrlRespectUtil.url = requestUriString;
				}
			}
			catch (Exception)
			{
			}
			finally
			{
				if (httpWebRequest != null)
				{
					httpWebRequest.Abort();
					httpWebRequest = null;
				}
				if (httpWebResponse != null)
				{
					httpWebResponse.Close();
					httpWebRequest = null;
				}
			}
		}

		// Token: 0x040002C6 RID: 710
		private static object thisLock = new object();

		// Token: 0x040002C7 RID: 711
		private static volatile bool flag;

		// Token: 0x040002C8 RID: 712
		private static volatile string url;

		// Token: 0x040002C9 RID: 713
		private static volatile Dictionary<string, string> appFastUrlDict = new Dictionary<string, string>();

		// Token: 0x040002CA RID: 714
		private static HttpProxy proxy;
	}
}
